# == Schema Information
# Schema version: 38
#
# Table name: messages
#
#  id           :integer(11)     not null, primary key
#  sender_id    :integer(11)
#  receiver_id  :integer(11)
#  title        :string(255)
#  content      :text
#  content_html :text
#  created_at   :datetime
#  unread       :boolean(1)      default(TRUE)
#

class Message < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 20
  
  format_attribute :content
   
  belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
  belongs_to :receiver, :class_name => "User", :foreign_key => "receiver_id"
  
  validates_presence_of :title
  
  def after_create
    Mailer.deliver_message_notification(self)
  end
  
  def sender_name
    if self.sender_id == 0
      "系统消息"
    else
      self.sender.login
    end
  end
  
  def receiver_name
    self.receiver.login
  end
  
  def replyable?(user)
    sender_id != 0 && receiver_id == user.id
  end
  
  def own_by?(user)
    sender_id == user.id || receiver_id == user.id
  end
end
